package br.unicarioca.viaexpositus

class OrganizacaoController extends BaseAutenticacao  {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    static defaultAction = "list"

    @AnotacaoDeAcao(nomeDaAcao="Listar", padrao="ROLE_ADMINISTRADOR")
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [organizacaoInstanceList: Organizacao.list(params), organizacaoInstanceTotal: Organizacao.count()]
    }

    @AnotacaoDeAcao(nomeDaAcao="Salvar", padrao="ROLE_ADMINISTRADOR")
    def save = {
        def organizacaoInstance = new Organizacao(params)
        organizacaoInstance.nome = params.organizacao.nome

        def usuarioInstance = new Usuario(params)
        usuarioInstance.nome = params.usuario.nome
        usuarioInstance.ativo = true
        usuarioInstance.senha = authenticateService.encodePassword(params.senha)
        usuarioInstance.confirmacaoSenha = authenticateService.encodePassword(params.confirmacaoSenha)

        def perfil = Perfil.findByNome(Perfil.PERFIL_ORGANIZACAO)

        Perfil novoPerfil = new Perfil()
        novoPerfil.listaDePermissoes = []
        novoPerfil.nome = organizacaoInstance.nome
        novoPerfil.descricao = "Este é o perfil do administrador da organização."
        novoPerfil.gerarCodeNome()

        perfil.listaDePermissoes.each{
            it.perfil = it.perfil+","+novoPerfil.codenome
            novoPerfil.listaDePermissoes << it
        }

        usuarioInstance.perfis = []
        usuarioInstance.perfis << novoPerfil

        usuarioInstance.organizacao = organizacaoInstance

        novoPerfil.usuarios = []
        novoPerfil.addToUsuarios(usuarioInstance)

        organizacaoInstance.administrador = usuarioInstance

        if(usuarioInstance.validate() && organizacaoInstance.validate()){
            if (organizacaoInstance.save(flush: true) && usuarioInstance.save(flush: true) && novoPerfil.save(flush:true) ) {

                authenticateService.clearCachedRequestmaps()
                flash.message = "${message(code: 'default.created.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), organizacaoInstance.id])}"
                redirect(action: "list")
            } else {
                render(view: "edit", model: [organizacaoInstance: organizacaoInstance, usuarioInstance: usuarioInstance])
            }
        } else {
            render(view: "edit", model: [organizacaoInstance: organizacaoInstance, usuarioInstance: usuarioInstance])
        }
        
    }

    @AnotacaoDeAcao(nomeDaAcao="Editar", padrao="ROLE_ADMINISTRADOR")
    def edit = {

        if(params.id && params.id != "0"){
            def organizacaoInstance = Organizacao.get(params.id)
            if (organizacaoInstance) {
                return [ organizacaoInstance : organizacaoInstance, usuarioInstance:organizacaoInstance.administrador]
            }else{
                flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), params.id])}"
                redirect(action: "list")
            }
        } else {
            def organizacaoInstance = new Organizacao()
            return [organizacaoInstance: organizacaoInstance]
        }
    }

    @AnotacaoDeAcao(nomeDaAcao="Atualizar", padrao="ROLE_ADMINISTRADOR")
    def update = {
        def organizacaoInstance = Organizacao.get(params.id)
        if (organizacaoInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (organizacaoInstance.version > version) {
                    
                    organizacaoInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'organizacao.label', default: 'Organizacao')] as Object[], "Another user has updated this Organizacao while you were editing")
                    render(view: "edit", model: [organizacaoInstance: organizacaoInstance])
                    return
                }
            }
            organizacaoInstance.properties = params
            if (!organizacaoInstance.hasErrors() && organizacaoInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), organizacaoInstance.id])}"
                redirect(action: "edit", id: organizacaoInstance.id)
            }
            else {
                render(view: "edit", model: [organizacaoInstance: organizacaoInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), params.id])}"
            redirect(action: "list")
        }
    }

    @AnotacaoDeAcao(nomeDaAcao="Remover", padrao="ROLE_ADMINISTRADOR")
    def delete = {
        def organizacaoInstance = Organizacao.get(params.id)
        if (organizacaoInstance) {
            try {
                organizacaoInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), params.id])}"
                redirect(action: "edit", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'organizacao.label', default: 'Organizacao'), params.id])}"
            redirect(action: "list")
        }
    }
}
